package cc.shacocloud.mirage.utils.converter.support;

import cc.shacocloud.mirage.utils.converter.ConversionSupport;
import cc.shacocloud.mirage.utils.converter.TypeDescriptor;
import org.jetbrains.annotations.NotNull;

/**
 * 转换为 {@link Boolean} 类型的转换器
 *
 * @author 思追(shaco)
 */
public class ToBooleanConversion extends AbstractConversion implements ConversionSupport {
    
    @Override
    public boolean support(@NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) {
        Class<?> objectType = targetType.getObjectType();
        return Boolean.class.equals(objectType);
    }
    
    @Override
    public Object convert(@NotNull Object source, @NotNull TypeDescriptor sourceType, @NotNull TypeDescriptor targetType) {
        if (source instanceof Boolean) {
            return source;
        } else if (source instanceof Number) {
            // 0为false，其它数字为true
            return 0 != ((Number) source).intValue();
        }
        
        String str = convertToStr(source);
        return Boolean.parseBoolean(str);
    }
    
}
